<?php

namespace api\services\goods;

use api\extensions\ApiBaseService;

use common\models\goods\brand\GoodsBrandModel;
use common\services\cache\CommonCache;
use common\models\goods\goods\GoodsModel;
use api\services\goods\GoodsService;

/**
 * Desc 品牌管理服务类
 * @author WMX
 */
class GoodsBrandService extends ApiBaseService
{

    /**
     * 列表
     * @param array $params 参数 
     * **/
    public static function getList($params)
    {
        try {
            $mkey = 'BRAND_LIST_';
            // $data = CommonCache::getCache($mkey);
            // if ($data && empty($refresh)) {
            //     return self::jsonSuccess($data);
            // }
            $brand = GoodsBrandModel::getAll(['state' => GoodsBrandModel::STATE_ENABLE]);
            if (empty($brand)) {
                throw new \Exception('品牌数据异常');
            }

            $group = [];
            foreach ($brand as &$val) {
                $group[$val['sort']]['sub'][] = $val;
                $group[$val['sort']]['name'] = $val['sort'];
            }
            ksort($group);
            $group = array_values($group);
            CommonCache::setCache($mkey, $group);
            return self::jsonSuccess($group);
        } catch (\Exception $exc) {
            return self::jsonSuccess([]);
        }
    }

    /**
     * 品牌商品-top20
     * * */
    public static function getBrandGoodsTop($brand_id, $refresh = false)
    {
        // $mkey = 'BRAND_GOODS_TOP_' . $brand_id;
        // $data = CommonCache::getCache($mkey);
        // if ($data && empty($refresh)) {
        //     // return $data;
        // }

        $brand = GoodsBrandModel::getDataOne(['id' => $brand_id]);
        if (empty($brand)) {
            return [];
        }
        $brand['sales'] = GoodsModel::find()->where(['brand'=>$brand_id])->count();
        $brand_goods = GoodsModel::getDataAll(['brand' => $brand_id], 1, 20, 'sales desc');
        if (empty($brand_goods)) {
            return [];
        }
        $brand['goods'] = GoodsService::getGoodsInfo(array_column($brand_goods['list'], 'id'), 1, 1);
        // CommonCache::setCache($mkey, $brand, 60 * 60 * 5);
        return $brand;
    }
}
